import axios from 'axios'
import {
    message
} from 'antd'
import store from "@/store/store"
import services from '@/services.js'
const BASE_URL = process.env.NODE_ENV === 'development' ? '' : 'https://web.hqmpet.com'


const jsonApiList = '/market/api/admin/shopKeyword'
const Axios = axios.create({
    timeout: 20000
})

// 添加请求拦截器
Axios.interceptors.request.use(
    config => {
        // store.dispatch({
        //     type:'ResetPageActionTime'
        // })
        store.dispatch({
            type: 'OPENPAGELOADING'
        })
        // 将 token 添加到请求头
        let type = 'application/x-www-form-urlencoded;charset=UTF-8'
        if (config.url.includes('/json') || config.url.includes('/Json') || config.url.includes('/mock') || config.headers['Content-Type'] === 'application/json') {
            type = 'application/json;charset=UTF-8'
        } else {
            type = 'application/x-www-form-urlencoded;charset=UTF-8'
        }
        config.headers['Content-Type'] = type
        config.headers['sessionprefix'] = localStorage.getItem('sessionprefix')
        let token = sessionStorage.getItem('RSnetToken')
        if (token) {
            token && (config.headers.RSnetToken = token)
        }
        config.headers['Accept'] = '*/*'
        if (config.url.indexOf('/auth/captcha') > -1) {
            config.headers['Accept'] = 'image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8'
            config['responseType'] = 'arraybuffer'

        }
        return config
    },
    error => {
        store.dispatch({
            type: 'CLOSEPAGELOADING'
        })
        return Promise.reject(error)
    }
)

// 添加响应拦截器
Axios.interceptors.response.use(
    response => {
        store.dispatch({
            type: 'CLOSEPAGELOADING'
        })
        if (response.status === 200 && response.data.code === 0) {
            return Promise.resolve(response)
        } else {
            if (response.config.url.includes('export')) {
                return Promise.resolve(response)
            }
            if (typeof response.data === 'object' && response.data.hasOwnProperty('codeMessage')) {
            // if (typeof response.data === 'object' && response.data.hasOwnProperty('codeMessage')&&response.config.url.indexOf('auth/admin/login') <= -1) {

                message.error(response.data.codeMessage)
            }
            if (response.config.url.indexOf('/auth/captcha') > -1) {
                localStorage.setItem('sessionprefix', response.headers['sessionprefix'])
                return Promise.resolve(response)
            }
            return Promise.resolve(response)

        }
    },
    error => {
        if (error.message === 'timeout of 10000ms exceeded') {
            message.error('请求超时！');
        }
        store.dispatch({
            type: 'CLOSEPAGELOADING'
        })
        // 比如： token 过期， 无权限访问， 路径不存在， 服务器问题等
        switch (error.response.status) {
            case 400:
                message.error('400：' + error)
                break
            case 401:
                message.error('401：' + error)
                break
            case 403:
                message.error('403：' + error)
                break
            case 404:
                message.error('404：' + error)
                break
            case 500:
                message.error('500：' + error)
                break
            default:
                message.error('其他错误信息')
        }
        //message.error(error)
        return Promise.reject(error)
    }
)

export function get(url, params) {
    let reg = /^\/app\//
    let baseUrl = BASE_URL


    if (reg.test(url)) {
        baseUrl = ''
    }
    return new Promise((resolve, reject) => {
        Axios.get(baseUrl + url, {
            params: params
        })
            .then(res => {
                resolve(res.data);
            })
            .catch(err => {
                message.error(err.data)
                reject(err.data)
            })
    });
}

/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */

export function post(url, params = {}, config) {
    let reg = /^\/app\//
    let baseUrl = BASE_URL
    // baseUrl = getBASE_URL(url)
    if (reg.test(url)) {
        baseUrl = ''
    }
    let arr = Object.values(params)
    let data = '';
    Object.keys(params).forEach((key, index) => {
        let d = ''
        index !== Number(arr.length - 1) ? d = key + '=' + encodeURIComponent(params[key]) + '&' : d = key + '=' + encodeURIComponent(params[key])
        data += d
    });
    return new Promise((resolve, reject) => {
        Axios.post(baseUrl + url, data, { ...config })
            .then(res => {
                resolve(res.data);
            })
            .catch(err => {
                reject(err.data)
            })
    });
}

/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function postBlob(url, params = {}) {
    let arr = Object.values(params)
    let data = '';
    Object.keys(params).forEach((key, index) => {
        let d = ''
        index !== Number(arr.length - 1) ? d = key + '=' + params[key] + '&' : d = key + '=' + params[key]
        data += d
    });
    return new Promise((resolve, reject) => {
        Axios.post(BASE_URL + url, data, {
            responseType: 'arraybuffer'
        })
            .then(res => {
                resolve(res.data);
            })
            .catch(err => {
                reject(err.data)
            })
    });
}

/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function postJson(url, params = {}) {
    const headers = {
        'Content-Type': 'application/json'
    }
    return new Promise((resolve, reject) => {
        Axios.post(BASE_URL + url, params, {
            headers
        })
            .then(res => {
                resolve(res.data);
            })
            .catch(err => {
                reject(err.data)
            })
    });
}

/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function postMedia(url, params = {}) {
    return new Promise((resolve, reject) => {
        Axios.post(url, params)
            .then(res => {
                resolve(res.data);
            })
            .catch(err => {
                reject(err.data)
            })
    });
}
/**
 * put请求
 */
export function put(url, params = {}) {
    let arr = Object.values(params)
    let data = '';
    Object.keys(params).forEach((key, index) => {
        let d = ''
        index !== Number(arr.length - 1) ? d = key + '=' + encodeURIComponent(params[key]) + '&' : d = key + '=' + encodeURIComponent(params[key])
        data += d
    });
    return new Promise((resolve, reject) => {
        Axios.put(BASE_URL + url, data)
            .then(res => {
                resolve(res.data);
            })
            .catch(err => {
                reject(err.data)
            })
    });
}
/**
 * delete
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function deletefn(url, params) {
    return new Promise((resolve, reject) => {
        Axios.delete(BASE_URL + url, {
            params: params
        })
            .then(res => {
                resolve(res.data);
            })
            .catch(err => {
                reject(err.data)
                message.error(err.data)
            })
    });
}
const getBASE_URL = (url) => {
    // const reg = /[^/]+/g
    // const match = url.match(reg)
    const proxyUrl = Object.keys(services.mapService).find(key => {
        const reg = RegExp("^" + key)
        if (reg.test(url)) {
            return key
        }
    })
    return ''
}
